
# Set up the packages, options, and working directory path
pacman::p_load(tidyverse, RColorBrewer, haven, sf, tidycensus)
set.seed(42)
options(scipen=999)
if (Sys.info()[['user']] == "alal") {
  root = "/home/alal/Dropbox/1_Research/ElecAdminFunding/ElecAdminFundingReplication"
  theme_set(lal_plot_theme())
} else {
  root = "~/Dropbox/ElecAdminFunding/ElecAdminFundingReplication"
  theme_set(theme_minimal())
}


##
# Make map of grant receipt
##

# Define the color palette we'll use throughout
colors_base = brewer.pal(5, "Blues")
map_colors = c(colors_base[2], colors_base[4], "#616161")

# Set up the analysis file
ctcl = haven::read_dta(file.path(root, "/modified_data/ctcl.dta")) %>%
  mutate(treat_pct = treat*100)

# Build the treatment map
treat_map = ctcl %>% # pull in treatment status by county
	filter(policy_year==2020) %>%
	select(state, fips, treat) %>% 
	merge(mutate(county_laea, fips = as.numeric(GEOID)), # add in the county geographies 
		by = "fips", all.y = TRUE) %>%
	st_as_sf() %>%
	mutate(treat = case_when( # turn treat into a label string
			treat==1 ~ " Received Grant",
			treat==0 ~ " Did Not Receive Grant",
			is.na(treat) ~ "Not in Scope")) %>% # set up the geography data for mapping
	ggplot() +
		geom_sf(aes(fill = treat)) + # plot the county treat status
		geom_sf(data = state_laea, # add state boundaries
			col = "#444444", lwd = .8, fill = NA) +
		scale_fill_manual(values = map_colors) + # use the map colors we set above
		theme_void() +
		labs(fill = "") +
		theme(legend.position = 'bottom',
		    legend.text = element_text(size = 25),
		    legend.key.size = unit(1.15, 'cm'))

# Save the treatment map as a pdf
ggsave(file.path(root, "output/treatmap.pdf"), plot=treat_map,
  width = 12, height = 10)


##
# Make a map of policy changes
##

# Make a list of states that limit private election administration donations
# data from https://www.ncsl.org/elections-and-campaigns/prohibiting-private-funding-of-elections
limits_grants = c("AL", "AZ", "AR", "FL", "GA", "ID", "IN", "IA", "KS", "KY",
  "MS", "MO", "NE", "ND", "OH", "OK", "PA", "SC", "SD", "TN", "TX", "UT", "VA", "WV")

# Build the policy response map
policy_map = usmap::us_map() %>% # set up state map data
  mutate(policy = ifelse(abbr %in% limits_grants, # flag states that ban grants
    "Limits Grants", "Does Not Limit Grants")) %>%
  select(fips, policy) %>%
  distinct() %>% # get the policy data down to a list of states
  usmap::plot_usmap(data=., values = "policy") + # make the map
    scale_fill_manual(values = map_colors) +
    theme_void() +
    labs(fill = "") +
    theme(legend.position = 'bottom',
          legend.text = element_text(size = 25),
          legend.key.size = unit(1.15, 'cm'))

# Save the policy response map
ggsave(file.path(root, "output/policy_map.pdf"), plot=policy_map,
  width = 12, height = 10)

